angular.module('bw.controller')
    //首页
    .controller('indexCtrl', ['ENV', '$compile', '$rootScope', '$scope', '$cookieStore', '$state', 'baseService', '$stateParams', 'appointmentService', 'toast', function(ENV, $compile, $rootScope, $scope, $cookieStore, $state, baseService, $stateParams, appointmentService, toast) {
        baseService.getToken();
        appointmentService.getWxSign({}, function(reseponse) {
            wx.config({
                debug: false, //是否弹出错误信息
                appId: ENV.appId,
                timestamp: reseponse.Data.Timestamp,
                nonceStr: reseponse.Data.NonceStr,
                signature: reseponse.Data.Signature,
                jsApiList: ['getLocation', 'scanQRCode']
            });
        });
        var websokitFn = function() {
            var head = document.getElementsByTagName('head');
            if (head && head.length) {
                head = head[0];
            } else {
                head = document.body;
            }
            var script = document.createElement('script');
            script.type = "text/javascript";
            head.appendChild(script);
            script.onload = script.onreadystatechange = function() {
                if ((!this.readyState) || this.readyState == "complete" || this.readyState == "loaded") {
                    $.connection.hub.url = ENV.sorket + "signalr";
                    var chat = $.connection.messageHub;
                    chat.client.getMessage = function(message) {
                        console.info(message);
                        $scope.$broadcast("signalrInfo", message);
                    };
                    //var token = prompt('Enter your token:', '');
                    $.connection.hub.qs = {
                        Bearer: localStorage.getItem("_token") ? JSON.parse(localStorage.getItem("_token")) : null
                    };
                    $.connection.hub.start().done(function() {});
                }
            };
            script.src = ENV.sorket + "signalr/hubs";
        }
        websokitFn();
    }])
    .controller('ongoingCtrl', ['ENV', 'toast', '$rootScope', '$scope', '$state', 'baseService', '$stateParams', 'appointmentService', 'baiduService', function(ENV, toast, $rootScope, $scope, $state, baseService, $stateParams, appointmentService, baiduService) {
        $('#viewport').attr('content','width=device-width, initial-scale=1, user-scalable=no');
        var RootFontSize = document.body.offsetWidth / 750 * 16;
        document.getElementsByTagName("html")[0].style.fontSize = RootFontSize + "px";
        $scope.appInfo = {};
        $scope.driverBox = {
            isShow: true, //是否显示司机和车辆信息
            isShowSure: false //是否显示确认到达按钮
        };
        $scope.noAction = $stateParams.noAction;
        var changeTime = 0;
        var intervalNumber = 5000;
        var ongoingTnterval;
        var map = new BMap.Map("map");
        var carMarker = '';
        var mineIcon = new BMap.Icon("../../imgs/header-mine.png", new BMap.Size(50, 50));
        var Icon = new BMap.Icon("../../imgs/header.png", new BMap.Size(50, 50));
        var getAppStatus = function() {
            appointmentService.getAppStatus({ "blId": $stateParams.blId }, function(reseponse) {
                if (reseponse.Status == 1 && reseponse.Data) {
                    var statu = { state: reseponse.Data.ChildStatus };
                    switch (reseponse.Data.ChildStatus) {
                        case 'ToSend': //  待接送
                            statu.text = "司机正在接其他乘客";
                            break;
                        case 'Completed': //  已完成
                            statu.text = "已完成";
                            break;
                        case 'Arrived': //  已到达
                            statu.text = "已到达";
                            $scope.driverBox.isShowSure = true;
                            baseService.setTitle("已到达");
                            break;
                        case 'Aboard': //  已上车
                            statu.text = "您已上车";
                            break;
                        case 'Cancel': //  取消
                            statu.text = "已取消";
                            break;
                        case 'PickUp': //  去接
                            statu.text = "司机正在接您的途中";
                            break;
                    }
                    $scope.appInfo.showState = statu;
                }
            });
        };
        var getCarLocation = function(callback) {
            var params = {
                ak: ENV.baiduMap.ak,
                service_id: ENV.baiduMap.service_id,
                entity_name: $scope.appInfo.DriverCode,
                start_time: parseInt($scope.appInfo.StatusChangeTime / 1000),
                end_time: parseInt((changeTime + intervalNumber) / 1000)
            };
            changeTime += intervalNumber;
            $.ajax({
                type: "get",
                async: false,
                data: params,
                url: "http://api.map.baidu.com/trace/v2/track/gethistory",
                dataType: "jsonp",
                jsonp: "callback", //传递给请求处理程序或页面的，用以获得jsonp回调函数名的参数名(一般默认为:callback)
                //jsonpCallback:"flightHandler",//自定义的jsonp回调函数名称，默认为jQuery自动生成的随机函数名，也可以写"?"，jQuery会自动为你处理数据
                success: function(json) {
                    if (json.status == 0 && json.start_point && json.end_point) {
                        var nowLong = json.end_point.longitude,
                            nowLat = json.end_point.latitude;
                        var pt = new BMap.Point(nowLong, nowLat);
                        var myIcon = new BMap.Icon("../../imgs/car.png", new BMap.Size(72, 38));
                        map.removeOverlay(carMarker)
                        carMarker = new BMap.Marker(pt, { icon: myIcon }); // 创建标注
                        map.addOverlay(carMarker);
                        //初始化地图路径规划，只初始化一次，后续状态变化再次初始化
                        if ($scope.isInit && json.start_point.loc_time != 0) {
                            var minPoint, distance = null;
                            var thisPoint = {
                                PickupLatitude: $scope.appInfo.PickupLatitude,
                                PickupLongitude: $scope.appInfo.PickupLongitude,
                                DestLatitude: $scope.appInfo.DestLatitude,
                                DestLongitude: $scope.appInfo.DestLongitude,
                                Status: $scope.appInfo.ChildStatus,
                                PickupTime: $scope.appInfo.PickupTime,
                                BLID: $scope.appInfo.BLID
                            }
                            var userArr = $scope.appInfo.OtherUserPickupInfo;
                            if (userArr) {
                                userArr.push(thisPoint);
                            } else {
                                userArr = [thisPoint];
                            }
                            //如果是接机
                            if ($scope.isJieji === true) {
                                for (var i in userArr) {
                                    var p = userArr[i];
                                    p.DestLatitude = isNaN(p.DestLatitude) ? 0 : p.DestLatitude;
                                    p.DestLongitude = isNaN(p.DestLongitude) ? 0 : p.DestLongitude;
                                    var thisDistance = (p.DestLongitude - nowLong) * (p.DestLongitude - nowLong) + (p.DestLatitude - nowLat) * (p.DestLatitude - nowLat)
                                    if (distance === null || distance > thisDistance) {
                                        distance = thisDistance;
                                        minPoint = p;
                                    }
                                    var point = new BMap.Point(p.DestLongitude, p.DestLatitude);
                                    var marker;
                                    if (p.BLID == $scope.appInfo.BLID) {
                                        marker = new BMap.Marker(point, { icon: mineIcon }); // 创建标注  
                                    } else {
                                        marker = new BMap.Marker(point, { icon: Icon }); // 创建标注  
                                    }
                                    map.addOverlay(marker);
                                }

                                var firstUserPoint = new BMap.Point(minPoint.DestLongitude, minPoint.DestLatitude);
                                $scope.driving.search(pt, firstUserPoint);
                                //如果是送机  
                            } else {

                                var waitingArr = [];
                                var aboardArr = [];
                                var endPoint = new BMap.Point($scope.appInfo.DestLongitude, $scope.appInfo.DestLatitude);
                                var pickUpPoint = null;
                                var pickUpUser;
                                var upCar = [];
                                var len = userArr.length;
                                //根据状态分组
                                for (var i in userArr) {
                                    if (userArr[i].Status === 'PickUp') {
                                        pickUpUser = userArr[i];
                                    } else if (userArr[i].Status === 'ToSend') {
                                        waitingArr.push(userArr[i]);
                                    } else if (userArr[i].Status === 'Aboard') {
                                        aboardArr.push(userArr[i]);
                                    }
                                }
                                //对待接的人进行排序 按时间
                                for (var j in waitingArr) {
                                    if (j < waitingArr.length - 1) {
                                        var n = parseInt(j) + 1;
                                        if (waitingArr[j].PickupTime > waitingArr[n].PickupTime) {
                                            var k = waitingArr[j];
                                            waitingArr[j] = waitingArr[n];
                                            waitingArr[n] = k;
                                        }
                                    }
                                }
                                //对已接的人进行排序 按时间
                                for (var j in aboardArr) {
                                    if (j < aboardArr.length - 1) {
                                        var n = parseInt(j) + 1;
                                        if (aboardArr[j].PickupTime > aboardArr[n].PickupTime) {
                                            var k = aboardArr[j];
                                            aboardArr[j] = aboardArr[n];
                                            aboardArr[n] = k;
                                        }
                                    }
                                }
                                //获取待接坐标
                                var pointArr = [];
                                //放入已接的乘客
                                for (var k in aboardArr) {
                                    pointArr.push(new BMap.Point(aboardArr[k].PickupLongitude, aboardArr[k].PickupLatitude));
                                    if (aboardArr[k].BLID == $scope.appInfo.BLID) {
                                        $scope.thisUserIndex = pointArr.length - 1;
                                    }
                                }
                                //放入正接的乘客
                                if (pickUpUser) {
                                    pointArr.push(new BMap.Point(pickUpUser.PickupLongitude, pickUpUser.PickupLatitude));
                                    if (pickUpUser.BLID == $scope.appInfo.BLID) {
                                        $scope.thisUserIndex = pointArr.length - 1;
                                    }
                                }
                                //放入待接的乘客
                                for (var k in waitingArr) {
                                    pointArr.push(new BMap.Point(waitingArr[k].PickupLongitude, waitingArr[k].PickupLatitude));
                                    if (waitingArr[k].BLID == $scope.appInfo.BLID) {
                                        $scope.thisUserIndex = pointArr.length - 1;
                                    }
                                }

                                $scope.driving.search(pt, endPoint, { waypoints: pointArr });
                            }
                        }
                        if (callback) callback();
                    }
                },
                error: function() {}
            });
        }
        appointmentService.getAppointmentInfo({ "blId": $stateParams.blId }, function(reseponse) {
            if (reseponse.Status == 1 && reseponse.Data) {
                //存储司机的ID和信息、以便从百度鹰眼获取司机轨迹数据
                $scope.appInfo = reseponse.Data;
                changeTime = $scope.appInfo.StatusChangeTime;
                if (reseponse.Data.TripType === 'EnterPort') {
                    $scope.isJieji = true;
                } else {
                    $scope.isSongji = true;
                }
                buildMap();
                $scope.isInit = true;
                getAppStatus();
                getCarLocation(function() {
                    $scope.isInit = false;
                });
                ongoingTnterval = window.setInterval(function() {
                    getCarLocation();
                }, intervalNumber);

                $scope.$on("$destroy", function() {
                    clearInterval(ongoingTnterval);
                });
            }
        });
        //状态改变
        $scope.$on("signalrInfo", function(msg) {
            if (msg.Data.BLID == $scope.appInfo.BLID) {
                getAppStatus();
                $scope.isInit = true;
            }
        });
        $scope.$on('$destroy', function() {
            $('#viewport').attr('content','width=device-width, initial-scale=0.5, user-scalable=no');
            var RootFontSize = document.body.offsetWidth / 750 * 16;
            document.getElementsByTagName("html")[0].style.fontSize = RootFontSize + "px";
        })
        //乘客确认已经到达
        $scope.sureArived = function() {
            appointmentService.sureArived({ "blId": $stateParams.blId }, function(reseponse) {
                console.log("其实应该去评价的");
                $state.go("appointmentList");
            });
        }

        //显示和隐藏司机和车辆信息
        $scope.switchOngoing = function() {
            $scope.driverBox.isShow = !$scope.driverBox.isShow;
        }

        function buildMap(argument) {
            map.enableScrollWheelZoom();
            map.centerAndZoom(new BMap.Point(104.072366, 30.662304), 16);
            $scope.driving = new BMap.DrivingRoute(map, {
                renderOptions: { map: map, autoViewport: true },
                onMarkersSet: function(routes) {
                    var len = routes.length;
                    if ($scope.isJieji === true) {
                        map.removeOverlay(routes[1].marker);
                    } else {
                        for (var i = 0; i < len; i++) {
                            if (i === 0 || i === len - 1) continue;
                            if (i - 1 == $scope.thisUserIndex) {
                                routes[i].Lm.setIcon(mineIcon);
                            } else {
                                routes[i].Lm.setIcon(Icon);
                            }
                        }
                    }
                },
                onPolylinesSet: function(lines) {
                    var len=lines.length;
                    for (var i = 0; i < len; i++) {
                        lines[i].Ui.setStrokeOpacity('0.9');lines[i].Ui.setStrokeColor('#08A600');
                        //lines[i].Ui.setStrokeWeight(5);
                    }
                }
            });
            /*var point = new BMap.Point(116.404, 39.915);
            map.centerAndZoom(point, 17);*/

            //添加乘客的maker
            /*if ($scope.appInfo.OtherUserPickupInfo && $scope.appInfo.OtherUserPickupInfo.length > 0) {
                angular.forEach($scope.appInfo.OtherUserPickupInfo, function(p, i) {
                    var point = new BMap.Point(p.PickupLongitude, p.PickupLatitude);
                    var marker = new BMap.Marker(point); // 创建标注  
                    map.addOverlay(marker);
                });
            }*/
        }
    }]);
